<template>
  <div class="main">
    <!-- 按钮区 -->
    <div class="action">
      <el-button type="primary" :icon="CirclePlus" @click="add">新增</el-button>
      <el-button type="danger" :icon="Delete" @click="deleteAll">删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table class="data-grid" :data="rolePermMappings" stripe border @row-click="tblRowClick" ref="tblRef">
      <el-table-column type="selection" align="center"/>
      <el-table-column prop="permId" label="权限编号" width="90"/>
      <el-table-column prop="perm.name" label="权限名称"/>
<!--      <el-table-column prop="perm.enabled" label="是否启用" width="90" align="center">-->
<!--        <template #default="scope">-->
<!--          <el-switch v-model="scope.row.perm.enabled" inline-prompt active-text="是" inactive-text="否"/>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="操作" width="110" align="center">
        <template #default="scope">
          <el-button size="small" type="danger" @click.stop="deleteRow(scope.row)" :icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 弹出新增对话框 -->
  <el-dialog :title="dialogTitle" v-model="showDialog" draggable :close-on-click-modal="false"
             @close="onCloseDialog()" style="width: 700px">
    <div>
      <el-form label-width="100" :model="rolePermModel" :rules="rules" ref="rolePermFormRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="权限编号：" prop="roleId">
              <x-perm-combo-grid v-model="rolePermModel.permId" placeholder="请选择权限"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="showDialog = false">取消</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<style scoped>
.main {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.data-grid {
  margin-top: 10px;
}
</style>

<script setup>
import {findRPAll,updateRolePerm,deleteRolePermById,saveRolePerm} from "@/api/RolePermApi.js";
import {ref, onMounted, toRaw} from 'vue';
import {CirclePlus, Delete} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import XPermComboGrid from "@/components/XPermComboGrid.vue";

const props = defineProps({
  //传入参数：角色编号
  roleId: {
    type: Number,//数字
    required: true//必填
  }
});

let rolePermMappings = ref();//所有角色-权限数据

onMounted(() => {
  findAll();
});

// 查询全部用户组
async function findAll() {
  let params = {
    roleId: props.roleId
  };
  let resp = await findRPAll(params);
  console.log(resp);
  if (resp.code==='200') {
    rolePermMappings.value = resp.data;
  }
}

///////////////////////////////////////////////////////////
const tblRef = ref();

function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row);
}

// 批量删除全部
function deleteAll() {
  let rows = tblRef.value.getSelectionRows();
  let ids = rows.map(t => t.id);
  if (ids.length === 0) {
    ElMessage.warning("请选择您要删除的行");
  } else {
    ElMessageBox.confirm("是否确认删除选中的行?", "警告", {
      type: "warning"
    }).then(() => {
      deleteByIds(ids);
    }).catch(error => {
      //do nothing
    });
  }
}

//删除当前前
function deleteRow(row) {
  ElMessageBox.confirm("是否确认删除选中的行?", "警告", {
    type: "warning"
  }).then(() => {
    deleteByIds([row.id]);
  }).catch(error => {
    //do nothing
  });
}

//根据id批量删除
async function deleteByIds(ids) {
  let resp = await deleteRolePermById(ids);
  if (resp.code==='200') {
    ElMessage.success("操作成功，共删除" + resp.data + "行");
    await findAll();//重新加载
  } else {
    ElMessage.error(resp.msg || "操作失败");
  }
}

///////////////////////////////////////////////////////////////
let dialogTitle = ref("新增权限");
let showDialog = ref(false);
let rolePermFormRef = ref();

// 添加或修改角色-权限的表单数据
let rolePermModel = ref({
  permId: null
});

const rules = {
  permId: [
    {required: true, message: "权限编号不可为空", trigger: "blur"}
  ]
};

//清空对话框
function onCloseDialog() {
  rolePermFormRef.value.resetFields();//清空表单内容
}

function add() {
  dialogTitle.value = "新增权限";
  showDialog.value = true;
}

//点击确定按钮，提交
function submit() {
  rolePermFormRef.value.validate(async valid => {
    if (valid) {
      let rolePerm = toRaw(rolePermModel.value);
      rolePerm.id = null;
      rolePerm.roleId = props.roleId;

      let resp;
      try {
        resp = await saveRolePerm(rolePerm);
      } catch (error) {
        //console.log(error);
        ElMessage.error(error.msg || "新增权限失败");
        return;
      }

      if (resp.code==='200') {
        ElMessage.success("新增权限成功");
        showDialog.value = false;//关闭窗口
        await findAll();
      } else {
        ElMessage.error(resp.msg || "新增权限失败");
      }
    } else {
      ElMessage.warning("输入不正确");
    }
  });
}
</script>